less,sass入门

吴龙淼 写于 2020-10-29

前言

LESS,SASS 为 Web 开发者带来了福音,它在 CSS 的语法基础之上,引入了变量,Mixin(混入),运算以及函数等功能,大大简化了 CSS 的编写,并且降低了 CSS 的维护成本

LESS 基本语法

1.声明变量

@myColor:red;
a {
  color: @myColor;
}

@property: color; //属性
body {
        background-@{property}:#333;
    }

2.混入 Mixin

.bordered {
  border-top: dotted 1px black;
  border-bottom: solid 2px black;
}


#menu a {
  color: #111;
  .bordered();
}

.post a {
  color: red;
  .bordered();
}

3.嵌套

&表示当前选择器的父元素

.component {
  width: 300px;
  @media (min-width: 768px) {
    width: 600px;
    @media  (min-resolution: 192dpi) {
      background-image: url(/img/retina2x.png);
    }
  }
  @media (min-width: 1280px) {
    width: 800px;
  }
}


.component {
  width: 300px;
}
@media (min-width: 768px) {
  .component {
    width: 600px;
  }
}
@media (min-width: 768px) and (min-resolution: 192dpi) {
  .component {
    background-image: url(/img/retina2x.png);
  }
}
@media (min-width: 1280px) {
  .component {
    width: 800px;
  }
}

4.import 导入

@import "文件路径"

6.运算

    @charset "UTF-8";

  /*运算*/
@num:5;

  ul {
    width: 100%*@num;
    li {
      width: 100%/@num;
    }
  }

7.继承

nav{
    width: 100px;
    height: 50px;
}
ul:extend(nav){
    background: #f00;
}

8.转义

@min768: ~"(min-width: 768px)";//可以简写为@min768: (min-width: 768px);
.element {
  @media @min768 {
    font-size: 1.2rem;
  }
}

@media (min-width: 768px) {
  .element {
    font-size: 1.2rem;
  }
}

9.映射

#colors() {
  primary: blue;
  secondary: green;
}

.button {
  color: #colors[primary];
  border: 1px solid #colors[secondary];
}

.button {
  color: blue;
  border: 1px solid green;
}

SASS 基本语法

1.定义变量

$width : 10px;
.meng {
    width : $width;
}

插值语句#{}

$name: foo;
$attr: border;
p.#{$name} {
  #{$attr}-color: blue;
}

p.foo {
  border-color: blue; }

2.嵌套

//&父选择器,多个父选择器都会传递
    ul{
         li{
            color:red;
            &:hover a{
                  color:#000;
               }
          }

    }

3.import

@import "base";

4.继承

.alert {
  text-align:center;
  &:hover{
    color:red;
  }
}

div{@extend .alert}

5.控制指令

@if
@else
@for $i from 1 through 3 []
@for $i from a to b  [)
@each $var in list
@while

6.自定义函数

$grid-width: 40px;
$gutter-width: 10px;

@function grid-width($n) {
  @return $n * $grid-width + ($n - 1) * $gutter-width;
}

#sidebar { width: grid-width(5); }

#sidebar {
  width: 240px; }

7.混入mixin

定义混入@mixin
@mixin large-text {
  font: {
    family: Arial;
    size: 20px;
    weight: bold;
  }
  color: #ff0000;
}

引用混入
.page-title {
  @include large-text;
  padding: 4px;
  margin-top: 10px;
}

.page-title {
  font-family: Arial;
  font-size: 20px;
  font-weight: bold;
  color: #ff0000;
  padding: 4px;
  margin-top: 10px; }